log1("Initializing Script Loader ...");

/**/

scriptName = "Unnamed Script";

self.port.on("setScriptName", setScriptName)

loadScriptAsync = (function ()
{
    var funcIndex = 0;
    var tasksNext = {};

    self.port.on('ScriptLoader::onScriptContentLoaded', onScriptContentLoaded);
    self.port.on('ScriptLoader::LoadPreloadScript', LoadPreloadScript)
    return realLoadScriptAsync;


    function LoadPreloadScript(url, index)
    {
        realLoadScriptAsync(url, function ()
        {
            onPreloadScriptRequestFinished(index)
        });
    }
    function onPreloadScriptRequestFinished(index)
    {
        self.port.emit("ScriptLoader::PreloadScriptLoaded", index);
    }
    function onScriptContentLoaded(arg)
    {
        try
        {
            eval(arg.content)
            if (tasksNext[arg.onFinished])
                tasksNext[arg.onFinished]();
        }
        catch(e)
        {
            log1("<Error>[ScriptLoader-Loading] : \n" +
                "File : " + arg.url + "\n" +
                "Line Number : " + e.lineNumber +  "\n" + 
                "Error Message : " + e.message + "\n");
        }
    }
    function realLoadScriptAsync(url, onFinished)
    {
        var curIndex = funcIndex++;
        log1("Loading script : " + url);
        tasksNext[curIndex] = onFinished;
        self.port.emit("ScriptLoader::LoadScriptHelp", { url: url, onFinished: curIndex });
    }
})()
self.port.emit("ScriptLoader::Initialized");

function setScriptName(name)
{
    scriptName = name ? name : scriptName;
}

function log1(arg)
{
    self.port.emit("log", "[ScriptLoader] : " + arg);
}

log = function log(arg)
{
    self.port.emit("log", "[Page Script:" + scriptName + "] : " + stringify(arg));
}

logerr = function logerr(arg)
{
    self.port.emit("log", "[<Error> Page Script:" + scriptName + "] : " + stringify(arg));
}
stringify = function stringify(obj)
{
    if (typeof obj === "undefined")
        return "undefined";
    if (typeof obj === "object")
        return JSON.stringify(obj);
    if (typeof obj === "function")
        return "function " + obj.name + "(...){ ... }";
    else
        return obj.toString();
}